package com.example.sharesinfo.ui;


import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.base.BaseUIActivity;
import com.example.sharesinfo.bmob.BmobManager;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.helper.FileHelper;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.example.sharesinfo.view.LodingView;

import org.json.JSONException;

import java.io.File;
import java.util.HashMap;
import java.util.Map;


public class PushSquareActivity extends BaseUIActivity implements View.OnClickListener {
    private static final String LOGTAG = "PushSquareActivity:";
    private ImageButton ib_return;
    private TextView tv_push;
    private EditText et_content;
    private TextView tv_content_size;
    private ImageView iv_error;
    private TextView tv_media_path;
    private LinearLayout ll_media;
    private LinearLayout ll_camera;
    private LinearLayout ll_ablum;
    private LinearLayout ll_media_type;
    private File uploadFile = null;
    private LodingView mLodingView;
    private String urlRoot = "http://119.23.221.142/api/talk/SendTalk?";

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 200:
                    mLodingView.hide();
                    Toast.makeText(PushSquareActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                    setResult(Activity.RESULT_OK);
                    finish();

                    break;
                case 404:
                    Toast.makeText(PushSquareActivity.this, "发布失败，请重试", Toast.LENGTH_SHORT).show();
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_push_square);
        initView();
    }

    private void initView() {
        mLodingView = new LodingView(this);
        mLodingView.setLodingText("正在发布...");
        ib_return = findViewById(R.id.ib_return);
        ib_return.setOnClickListener(this);
        tv_push = findViewById(R.id.tv_push);
        tv_push.setOnClickListener(this);
        et_content = findViewById(R.id.et_content);
        tv_content_size = findViewById(R.id.tv_content_size);
        iv_error = findViewById(R.id.iv_error);
        tv_media_path = findViewById(R.id.tv_media_path);
        ll_media = findViewById(R.id.ll_media);
        ll_camera = findViewById(R.id.ll_camera);
        ll_ablum = findViewById(R.id.ll_ablum);
        ll_media_type = findViewById(R.id.ll_media_type);
        iv_error.setOnClickListener(this);
        ll_camera.setOnClickListener(this);
        ll_ablum.setOnClickListener(this);

        //输入框监听
        et_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tv_content_size.setText(s.length() + "/140");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_return:
                finish();
                break;
            case R.id.tv_push:
                inputSquare();
                break;
            case R.id.iv_error:
                ll_media_type.setVisibility(View.VISIBLE);
                ll_media.setVisibility(View.GONE);
                uploadFile = null;
                //MediaType = SquareSet.PUSH_TEXT;
                break;
            case R.id.ll_camera:
                FileHelper.getInstance().toCamera(this);
                break;
            case R.id.ll_ablum:
                FileHelper.getInstance().toAlbum(this);
                break;

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case FileHelper.CAMEAR_REQUEST_CODE:
                    uploadFile = FileHelper.getInstance().getTempFile();
                    LogUtils.i(LOGTAG + uploadFile.getPath());
                    if (!TextUtils.isEmpty(uploadFile.getPath())) {
                        LogUtils.i(LOGTAG + "相机返回路径不为空");
                        if (uploadFile.getPath().endsWith(".jpg")
                                || uploadFile.getPath().endsWith(".JPG")
                                || uploadFile.getPath().endsWith(".png")
                                || uploadFile.getPath().endsWith(".PNG")
                                || uploadFile.getPath().endsWith(".jpeg")
                                || uploadFile.getPath().endsWith(".JPEG")
                        ) {
                            LogUtils.i(LOGTAG + "相机返回" + "图片");
                            tv_media_path.setText("图片");
                        }
                        ll_media_type.setVisibility(View.GONE);
                        ll_media.setVisibility(View.VISIBLE);
                    }
                    break;
                case FileHelper.ALBUM_REQUEST_CODE:
                    if (data != null) {
                        Uri uri = data.getData();
                        LogUtils.i("path: " + uri);
                        String path = FileHelper.getInstance().
                                getFilePathByUri(PushSquareActivity.this, uri);
                        if (path == null) {
                            path = FileHelper.getInstance().
                                    getRealPathFromURI(PushSquareActivity.this, uri);
                        }
                        if (!TextUtils.isEmpty(path)) {
                            if (path.endsWith(".jpg")
                                    || path.endsWith(".JPG")
                                    || path.endsWith(".png")
                                    || path.endsWith(".PNG")
                                    || path.endsWith(".jpeg")
                                    || path.endsWith(".JPEG")
                            ) {
                                tv_media_path.setText("图片");
                            }
                            uploadFile = new File(path);
                            LogUtils.i(LOGTAG + "相册" + uploadFile.getPath());
                            ll_media_type.setVisibility(View.GONE);
                            ll_media.setVisibility(View.VISIBLE);
                        }
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 发布到广场
     */
    private void inputSquare() {
        final String content = et_content.getText().toString().trim();
        if (TextUtils.isEmpty(content) && uploadFile == null) {
            Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
            return;
        }
        mLodingView.show();
        if (uploadFile != null) {
            LogUtils.i(LOGTAG + "图片不为空" + uploadFile.getPath());
            //上传文件
            BmobManager.getInstance().uploadHeadPhoto(uploadFile, new BmobManager.OnUploadPhotoListener() {
                @Override
                public void OnSuccess(String imgurl) {
                    push(content, imgurl);
                }

                @Override
                public void OnFailed(BmobException e) {

                }
            });
        } else {
            push(content, "");
        }
    }

    /**
     * 发表
     *
     * @param content
     * @param path
     */
    private void push(String content, String path) {
        Map<String, String> datas = new HashMap<>();
        datas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
        datas.put("Content", content);
        datas.put("PictureUrl", path);
        OkHttpUtils.getInstance().Post(urlRoot, null, datas,
                null, null, new OkHttpUtils.okHttpListener() {
                    Message message = mHandler.obtainMessage();

                    @Override
                    public void OnSuccess(String s, int code) throws JSONException {
                        LogUtils.i(LOGTAG + s);
                        message.what = code;
                        mHandler.sendMessage(message);
                    }

                    @Override
                    public void OnFailed(String s) {
                        message.what = 404;
                        mHandler.sendMessage(message);
                    }
                });
        if (path.equals("")) {
            //纯文本
            LogUtils.i(LOGTAG + content);
        } else {
            //图片
            LogUtils.i(LOGTAG + path);
        }

    }
}
